package com.fan.shop.dao;

import java.util.ArrayList;
import java.util.List;

import javax.inject.Named;

import org.hibernate.Criteria;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.criterion.Restrictions;

import com.fan.shop.domain.Brand;
import com.fan.shop.domain.Item;

@Named("brandDao")
public class BrandDaoImpl implements BrandDao {

	private SessionFactory sessionFactory;

	/**
	 * Get Hibernate Session Factory
	 * 
	 * @return SessionFactory - Hibernate Session Factory
	 */
	public SessionFactory getSessionFactory() {
		return sessionFactory;
	}

	/**
	 * Set Hibernate Session Factory
	 * 
	 * @param SessionFactory
	 *            - Hibernate Session Factory
	 */
	public void setSessionFactory(SessionFactory sessionFactory) {
		this.sessionFactory = sessionFactory;
	}

	public Brand getBrand(String name) {
		Brand brand = (Brand) sessionFactory.getCurrentSession().get(
				Brand.class, name);
		return brand;
	}

	@SuppressWarnings("unchecked")
	public List<Brand> getAllBrands() {
		List<Brand> brands = sessionFactory.getCurrentSession()
				.createCriteria(Brand.class).list();
		return brands;
	}

	public int getSize() {
		return getAllBrands().size();
	}

	public void addBrand(Brand brand) {
		sessionFactory.getCurrentSession().save(brand);
	}

	public void updateStock(Brand brand) {
		sessionFactory.getCurrentSession().update(brand);
	}

	public void deleteBrand(Brand brand) {
		sessionFactory.getCurrentSession().delete(brand);
	}

	public boolean hasBrand(String name) {
		if (getBrand(name) == null) {
			return false;
		} else {
			return true;
		}
	}

	public List<String> getColumnNames() {
		List<String> columns = new ArrayList<String>();
		columns.add("Name");
		columns.add("Description");
		columns.add("Icon");
		columns.add("Enabled");
		return columns;
	}

	@SuppressWarnings("unchecked")
	public List<Item> getItemsWithBrand(String brand) {
		Session session = sessionFactory.getCurrentSession();
		Criteria criteria = session.createCriteria(Item.class);
		criteria.add(Restrictions.eq("brand", brand));
		return criteria.list();
	}

}
